// 引入API
const { appointmentApi } = require("../../utils/api.js");
// 引入工具函数
const { formatTime } = require("../../utils/util.js");

Page({
  data: {
    // 搜索相关
    searchValue: "",

    // 筛选相关
    activeTab: "all",
    filterDate: "", // 日期筛选条件
    showDatePicker: false, // 是否显示日期选择器
    // 移除日期范围限制，只设置默认日期
    defaultDate: new Date(), // 默认日期为今天

    // 列表相关
    appointmentList: [],
    loading: false,
    finished: false,
    refreshing: false,

    // 分页相关
    page: 1,
    pageSize: 10000000,

    // 对话框相关
    showCancelDialog: false,
    cancelAppointmentId: null,

    // 用户设置
    userSettings: {
      setting2: "",
      setting3: "",
    },

    // 统计相关
    totalCount: 0,
    pendingCount: 0,
    cancelledCount: 0,

    // 用户相关
    userInfo: null,
    isAdmin: false,

    // 请假数据
    leaveDays: {},
  },

  onLoad() {
    this.checkUserAndLoadData();
    this.loadLeaveDays();
    this.loadUserSettings();
  },

  /**
   * 加载用户设置
   */
  async loadUserSettings() {
    try {
      const { settingsApi } = require("../../utils/api.js");
      const result = await settingsApi.getUserSettings();

      if (result && result.code === 0) {
        this.setData({
          userSettings: result.data,
        });
      }
    } catch (error) {
      console.log("用户设置API异常:", error);
    }
  },

  /**
   * 加载请假数据
   */
  loadLeaveDays() {
    try {
      const leaveDays = wx.getStorageSync("leaveDays") || {};
      this.setData({
        leaveDays: leaveDays,
      });
    } catch (error) {}
  },

  /**
   * 请求订阅消息授权（传入两个模板ID）
   */
  requestAdminSubscribeMessage() {
    return new Promise((resolve) => {
      wx.requestSubscribeMessage({
        tmplIds: [
          "o7WljBjHOvNPXVvRdRO9pHFIOLO_pgbz3oc-WI4lng0", // 取消预约通知模板
          "ktex3oGhX7Bp8heWLu5dM10pRwXvtrQHEIkHNcNVGAQ", // 新预约通知模板
        ],
        success: (res) => {
          console.log("订阅消息结果:", res);
          // 严格要求两个模板都必须授权成功
          const templateIds = [
            "o7WljBjHOvNPXVvRdRO9pHFIOLO_pgbz3oc-WI4lng0",
            "ktex3oGhX7Bp8heWLu5dM10pRwXvtrQHEIkHNcNVGAQ",
          ];

          // 使用数组方式获取所有模板的授权状态
          const statuses = templateIds.map((tmplId) => res[tmplId]);
          console.log("模板授权状态:", statuses);

          // 必须两个模板都授权成功（使用 every 检查）
          const allAccepted = templateIds.every(
            (tmplId) => res[tmplId] === "accept"
          );

          if (allAccepted) {
            wx.showToast({
              title: "已开启所有消息通知",
              icon: "success",
            });
          } else {
            wx.showModal({
              title: "授权不完整",
              content:
                templateIds
                  .map((tmplId, index) => {
                    const status = res[tmplId];
                    const statusText =
                      status === "accept"
                        ? "✅已授权"
                        : status === "reject" || status === "ban"
                        ? "❌已拒绝"
                        : "⚠️未授权";
                    return `${index + 1}. ${statusText}`;
                  })
                  .join("\n") + "\n\n请重新开启以确保所有通知都能接收。",
              showCancel: false,
            });
          }
          resolve(res);
        },
        fail: (err) => {
          console.error("订阅消息失败:", err);
          resolve(null);
        },
      });
    });
  },

  /**
   * 检查用户身份并加载数据
   */
  checkUserAndLoadData() {
    const userInfo = wx.getStorageSync("userInfo");

    if (!userInfo) {
      // 用户未注册，跳转到注册页面
      wx.showModal({
        title: "需要注册",
        content: "请先注册用户信息才能查看预约记录",
        showCancel: false,
        confirmText: "去注册",
        success: () => {
          wx.navigateTo({
            url: "/pages/register/index",
          });
        },
      });
      return;
    }

    // 检查是否为管理员
    const isAdmin = userInfo.isAdmin || userInfo.role === "admin";

    this.setData({
      userInfo: userInfo,
      isAdmin: isAdmin,
    });

    // 如果是管理员，检查是否需要请求订阅消息授权
    if (isAdmin) {
      const hasRequestedAdminSubscribe = wx.getStorageSync(
        "hasRequestedAdminSubscribe"
      );
      if (!hasRequestedAdminSubscribe) {
        // 延迟一下，等页面加载完成后再弹出
        setTimeout(() => {
          wx.showModal({
            title: "开启消息通知",
            content: "开启后，当有新预约时您将收到微信通知。是否现在开启？",
            confirmText: "开启",
            cancelText: "暂不",
            success: (res) => {
              if (res.confirm) {
                this.requestAdminSubscribeMessage();
              }
              // 无论是否同意，都记录已请求过，避免重复弹出
              wx.setStorageSync("hasRequestedAdminSubscribe", true);
            },
          });
        }, 1000);
      }
    }

    // 加载预约数据
    this.loadAppointmentList();
  },

  async onShow() {
    // 页面显示时刷新数据
    this.loadLeaveDays();
    // 如果还没有数据，加载第一页
    if (!this.data.appointmentList || this.data.appointmentList.length === 0) {
      this.loadAppointmentList();
    }
  },

  // 下拉刷新
  async onRefresh() {
    this.setData({
      refreshing: true,
    });
    // 重新加载请假数据
    this.loadLeaveDays();
    // 重置分页并重新加载数据
    this.setData({
      page: 1,
      finished: false,
      appointmentList: [],
    });
    await this.loadAppointmentList();
  },

  // 上拉加载更多
  onLoadMore() {
    if (this.data.finished) return;
    // 确保请假数据是最新的
    this.loadLeaveDays();
    this.loadAppointmentList();
  },

  // 搜索输入
  onSearchChange(event) {
    this.setData({
      searchValue: event.detail,
    });
    // 延迟搜索，避免频繁请求
    clearTimeout(this.searchTimer);
    this.searchTimer = setTimeout(() => {
      // 搜索时重置分页并重新加载数据
      this.setData({
        page: 1,
        finished: false,
        appointmentList: [],
      });
      this.loadAppointmentList();
    }, 500);
  },

  // 切换标签
  onTabChange(event) {
    const activeTab = event.detail.name;
    this.setData({
      activeTab: activeTab,
    });
    // 切换标签时重置分页并重新加载数据
    this.setData({
      page: 1,
      finished: false,
      appointmentList: [],
    });
    this.loadAppointmentList();
  },

  // 显示日期选择器
  showDatePicker() {
    this.setData({
      showDatePicker: true,
    });
  },

  // 隐藏日期选择器
  hideDatePicker() {
    this.setData({
      showDatePicker: false,
    });
  },

  // 确认日期选择
  onDateConfirm(event) {
    const value = event.detail;
    const dateTime = formatTime(value);

    // 正确格式化日期，避免时区问题
    const year = value.getFullYear();
    const month = String(value.getMonth() + 1).padStart(2, "0");
    const day = String(value.getDate()).padStart(2, "0");
    const formattedDate = `${year}-${month}-${day}`;

    this.setData({
      filterDate: formattedDate,
      showDatePicker: false,
    });
    // 重新筛选数据
    this.setData({
      page: 1,
      finished: false,
      appointmentList: [],
    });
    this.loadAppointmentList();
  },

  // 清除日期筛选
  clearDateFilter() {
    this.setData({
      filterDate: "",
    });
    // 重新筛选数据
    this.setData({
      page: 1,
      finished: false,
      appointmentList: [],
    });
    this.loadAppointmentList();
  },

  // 选择今天
  selectToday() {
    const today = new Date();
    const todayStr = today.toISOString().split("T")[0]; // 格式化为 YYYY-MM-DD
    this.setData({
      filterDate: todayStr,
      showDatePicker: false,
    });
    // 重新筛选数据
    this.setData({
      page: 1,
      finished: false,
      appointmentList: [],
    });
    this.loadAppointmentList();
  },

  // 刷新数据
  refreshData() {
    this.setData({
      page: 1,
      finished: false,
      appointmentList: [],
    });
    this.loadAppointmentList();
  },

  // 按tab过滤预约
  async filterAppointmentsByTab(activeTab) {
    // 如果还没有数据，先加载第一页
    if (!this.data.appointmentList || this.data.appointmentList.length === 0) {
      await this.loadAppointmentList();
      return;
    }

    // 使用现有的预约数据进行过滤
    let allAppointments = this.data.appointmentList || [];
    // 格式化预约数据，确保有appointment_date_raw字段
    let filteredAppointments = allAppointments.map((item) => {
      const formatted = {
        ...item,
        appointment_date_raw: item.appointment_date || "", // 确保有原始日期字段
        appointment_date: this.formatDateOnly(item.appointment_date || ""), // 格式化显示日期
        // 确保其他必要字段存在
        customer_name: item.customer_name || "未知用户",
        customer_phone: item.customer_phone || "",
        queue_number: item.queue_number || 1,
        appointment_time: item.appointment_time
          ? this.formatAppointmentTime(item.appointment_time)
          : "",
        status: item.status || 1,
      };

      return formatted;
    });

    // 根据tab过滤
    if (activeTab === "pending") {
      filteredAppointments = filteredAppointments.filter(
        (item) => item.status === 1
      );
    } else if (activeTab === "completed") {
      filteredAppointments = filteredAppointments.filter(
        (item) => item.status === 3
      );
    } else if (activeTab === "cancelled") {
      filteredAppointments = filteredAppointments.filter(
        (item) => item.status === 4
      );
    }

    // 根据日期筛选
    if (this.data.filterDate) {
      filteredAppointments = filteredAppointments.filter((item) => {
        // 将原始日期格式化为YYYY-MM-DD格式进行比较
        const itemDate = this.formatDateOnly(
          item.appointment_date_raw || item.appointment_date || ""
        );
        const filterDate = this.formatDateOnly(this.data.filterDate);
        const matches = itemDate === filterDate;

        return matches;
      });
    }

    // 应用搜索过滤
    if (this.data.searchValue) {
      filteredAppointments = filteredAppointments.filter(
        (item) =>
          item.customer_name.includes(this.data.searchValue) ||
          item.customer_phone.includes(this.data.searchValue)
      );
    }

    // 按预约日期和排队号码排序 - 最新日期在前，同一天内按排队号码倒序
    filteredAppointments.sort((a, b) => {
      // 首先按预约日期排序（降序，最新日期在前）
      const dateA = new Date(a.appointment_date_raw || "1970-01-01");
      const dateB = new Date(b.appointment_date_raw || "1970-01-01");

      if (dateA.getTime() !== dateB.getTime()) {
        return dateB - dateA; // 降序排列，最新日期在前
      }

      // 如果日期相同，按排队号码排序（降序，大号码在前）
      const queueA = a.queue_number || 0;
      const queueB = b.queue_number || 0;

      return queueB - queueA; // 排队号码倒序，大号码在前
    });

    // 转换数据格式
    const formattedList = filteredAppointments.map((item) => {
      // 检查是否为其他人创建的预约（仅对管理员显示）
      const isDifferentPhone =
        this.data.isAdmin &&
        this.data.userInfo &&
        item.user_id !== this.data.userInfo.id;

      return {
        id: item.id,
        customer_name: item.customer_name || "未知用户",
        customer_phone: item.customer_phone || "",
        appointment_date: this.formatDateOnly(item.appointment_date || ""),
        appointment_date_raw: item.appointment_date || "", // 保存原始日期用于排序
        product_title: item.product_title || "", // 预约商品标题
        customer_remark: item.customer_remark || "",
        queue_number: item.queue_number || 1,
        appointment_time: item.appointment_time
          ? this.formatAppointmentTime(item.appointment_time)
          : "",
        estimated_time: item.estimated_time
          ? this.formatEstimatedTime(item.estimated_time)
          : "",
        status:
          item.status === 1
            ? "pending"
            : item.status === 3
            ? "completed"
            : "cancelled",
        effect_images: this.processImageUrls(item.effect_images || []),
        // 预约关系信息
        created_by: item.created_by || "",
        appointed_for: item.appointed_for || "",
        is_self_appointed: item.is_self_appointed || false,
        is_different_phone: isDifferentPhone,
        // 原始数据，用于权限判断
        original_data: item,
      };
    });

    if (formattedList.length > 0) {
    }

    this.setData({
      appointmentList: formattedList,
      loading: false,
      refreshing: false,
    });
  },

  // 从服务器加载预约数据
  async loadAppointmentsFromServer() {
    try {
      const result = await appointmentApi.getAppointments();

      if (result.code === 0 && result.data) {
        // 服务器返回的数据结构是 {list: appointments, total: total, ...}
        const appointments = result.data.list || result.data;
        // 将服务器数据保存到本地存储（用于其他功能）
        wx.setStorageSync("appointments", appointments);
        // 返回数据供当前方法使用
        return appointments;
      } else {
        return [];
      }
    } catch (error) {
      return [];
    }
  },

  // 加载预约列表
  async loadAppointmentList() {
    if (this.data.loading || this.data.finished) return;

    this.setData({
      loading: true,
    });

    try {
      // 从后端API获取预约数据，使用当前页码
      const params = {
        page: this.data.page || 1,
        pageSize: this.data.pageSize || 10,
      };

      // 如果有日期筛选条件，传递给后端
      if (this.data.filterDate) {
        params.date = this.data.filterDate;
      }

      const result = await appointmentApi.getAppointments(params);

      let allAppointments = [];
      if (result.code === 0 && result.data && result.data.list) {
        allAppointments = result.data.list;
      } else if (result.code === 0 && Array.isArray(result.data)) {
        allAppointments = result.data;
      }

      // 确保 allAppointments 是数组
      if (!Array.isArray(allAppointments)) {
        allAppointments = [];
      }

      // 注意：不再重新加载工作时间数据，避免覆盖工作时间设置页面的修改
      // 工作时间数据应该从工作时间设置页面管理

      // 去重（基于ID）
      const uniqueAppointments = allAppointments.filter(
        (item, index, self) => index === self.findIndex((t) => t.id === item.id)
      );

      // 应用搜索和筛选
      let filteredList = uniqueAppointments;

      // 搜索过滤
      if (this.data.searchValue) {
        filteredList = filteredList.filter(
          (item) =>
            item.customer_name.includes(this.data.searchValue) ||
            item.customer_phone.includes(this.data.searchValue)
        );
      }

      // 状态过滤
      if (this.data.activeTab !== "all") {
        const statusMap = {
          pending: 1,
          completed: 3,
          cancelled: 4,
        };
        filteredList = filteredList.filter(
          (item) => item.status === statusMap[this.data.activeTab]
        );
      }

      // 日期过滤 - 现在由后端处理，前端不需要再过滤
      // 如果后端没有正确处理日期参数，这里保留作为备用
      if (this.data.filterDate && !params.date) {
        filteredList = filteredList.filter((item) => {
          // 将原始日期格式化为YYYY-MM-DD格式进行比较
          const itemDate = this.formatDateOnly(item.appointment_date || "");
          const filterDate = this.formatDateOnly(this.data.filterDate);
          const matches = itemDate === filterDate;

          return matches;
        });
      }

      // 转换数据格式以匹配页面显示
      const formattedList = filteredList.map((item) => {
        // 检查是否为其他人创建的预约（仅对管理员显示）
        const isDifferentPhone =
          this.data.isAdmin &&
          this.data.userInfo &&
          item.user_id !== this.data.userInfo.id;

        return {
          id: item.id,
          customer_name: item.customer_name || "未知用户",
          customer_phone: item.customer_phone || "",
          appointment_date: this.formatDateOnly(item.appointment_date || ""),
          appointment_date_raw: item.appointment_date || "", // 保存原始日期用于排序
          appointment_time: item.appointment_time
            ? this.formatAppointmentTime(item.appointment_time)
            : "",
          product_title: item.product_title || "未设置", // 预约商品标题
          customer_remark: item.customer_remark || "",
          queue_number: item.queue_number || 1,
          appointment_time: item.appointment_time
            ? this.formatAppointmentTime(item.appointment_time)
            : "",
          estimated_time: item.estimated_time
            ? this.formatEstimatedTime(item.estimated_time)
            : "",
          status:
            item.status === 1
              ? "pending"
              : item.status === 3
              ? "completed"
              : "cancelled",
          effect_images: this.processImageUrls(item.effect_images || []),
          // 预约关系信息
          created_by: item.created_by || "",
          appointed_for: item.appointed_for || "",
          is_self_appointed: item.is_self_appointed || false,
          is_different_phone: isDifferentPhone,
          // 原始数据，用于权限判断
          original_data: item,
        };
      });

      // 追加数据到现有列表（服务器已经处理了分页）
      const appointmentList =
        this.data.page === 1
          ? formattedList
          : [...this.data.appointmentList, ...formattedList];

      // 对预约列表进行排序：按日期倒序，同一天内按排队号码倒序
      appointmentList.sort((a, b) => {
        // 首先按预约日期倒序排列
        const dateA = new Date(a.appointment_date);
        const dateB = new Date(b.appointment_date);

        if (dateA.getTime() !== dateB.getTime()) {
          return dateB.getTime() - dateA.getTime(); // 日期倒序
        }

        // 同一天内，按排队号码倒序排列
        const queueA = a.queue_number || 0;
        const queueB = b.queue_number || 0;

        return queueB - queueA; // 排队号码倒序
      });

      // 计算各状态的数量（使用所有数据，不仅仅是当前页）
      this.calculateAppointmentCounts(appointmentList);

      this.setData({
        appointmentList,
        loading: false,
        refreshing: false,
        finished: formattedList.length < (this.data.pageSize || 10),
        page: this.data.page + 1,
      });
    } catch (error) {
      this.setData({
        loading: false,
        refreshing: false,
      });
      wx.showToast({
        title: "加载失败，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 处理图片URL，添加服务器基础URL
   */
  processImageUrls(imageUrls) {
    if (!imageUrls || !Array.isArray(imageUrls)) {
      return [];
    }

    const config = require("../../config/server.js");
    const baseURL = config.getAPIBaseURL();
    // 静态文件服务器URL（不包含/api/v1前缀）
    const staticBaseURL = baseURL.replace("/api/v1", "");

    return imageUrls.map((url) => {
      // 如果URL已经是完整URL，直接返回
      if (url.startsWith("http://") || url.startsWith("https://")) {
        return url;
      }
      // 如果URL以/开头，添加静态文件服务器baseURL
      if (url.startsWith("/")) {
        return staticBaseURL + url;
      }
      // 其他情况，添加静态文件服务器baseURL和/
      return staticBaseURL + "/" + url;
    });
  },

  // 预览图片
  previewImage(event) {
    const { url, urls } = event.currentTarget.dataset;

    if (!url) {
      wx.showToast({
        title: "图片预览失败",
        icon: "none",
      });
      return;
    }

    // 处理urls，确保是数组格式
    let imageUrls = [];
    if (urls) {
      if (typeof urls === "string") {
        try {
          imageUrls = JSON.parse(urls);
        } catch (e) {
          imageUrls = [urls];
        }
      } else if (Array.isArray(urls)) {
        imageUrls = urls;
      } else {
        imageUrls = [url];
      }
    } else {
      imageUrls = [url];
    }

    wx.previewImage({
      current: url,
      urls: imageUrls,
      success: () => {
        // 图片预览成功
      },
      fail: (error) => {
        wx.showToast({
          title: "图片预览失败",
          icon: "none",
        });
      },
    });
  },

  // 取消预约
  cancelAppointment(event) {
    const id = event.currentTarget.dataset.id;
    this.setData({
      showCancelDialog: true,
      cancelAppointmentId: id,
    });
  },

  // 完成预约
  async completeAppointment(event) {
    const id = event.currentTarget.dataset.id;

    try {
      wx.showLoading({
        title: "处理中...",
      });

      // 调用后端API更新预约状态
      const result = await appointmentApi.updateAppointmentStatus(id, 3); // 3表示已完成

      if (result.code === 0) {
        // 更新本地存储中的预约状态
        this.updateAppointmentStatus(id, 3);

        wx.hideLoading();
        wx.showToast({
          title: "已完成",
          icon: "success",
        });

        // 刷新列表 - 重新加载数据
        this.setData({
          page: 1,
          finished: false,
          appointmentList: [],
        });
        await this.loadAppointmentList();
      } else {
        throw new Error(result.message || "操作失败");
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: "操作失败",
        icon: "none",
      });
    }
  },

  // 取消对话框关闭
  onCancelDialogClose() {
    this.setData({
      showCancelDialog: false,
      cancelAppointmentId: null,
    });
  },

  // 确认取消预约
  async onCancelConfirm() {
    const id = this.data.cancelAppointmentId;

    try {
      wx.showLoading({
        title: "取消中...",
      });

      // 调用后端API更新预约状态
      const result = await appointmentApi.updateAppointmentStatus(id, 4); // 4表示已取消

      if (result.code === 0) {
        // 更新本地存储中的预约状态
        this.updateAppointmentStatus(id, 4);

        wx.hideLoading();
        wx.showToast({
          title: "已取消",
          icon: "success",
        });

        // 刷新列表 - 重新加载数据
        this.setData({
          page: 1,
          finished: false,
          appointmentList: [],
        });
        await this.loadAppointmentList();
      } else {
        throw new Error(result.message || "取消预约失败");
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || "取消失败，请重试",
        icon: "none",
      });
    } finally {
      this.setData({
        showCancelDialog: false,
        cancelAppointmentId: null,
      });
    }
  },

  // 更新本地存储中的预约状态
  updateAppointmentStatus(id, status) {
    try {
      const appointments = wx.getStorageSync("appointments") || [];

      // 确保 appointments 是数组
      if (!Array.isArray(appointments)) {
        wx.setStorageSync("appointments", []);
        return;
      }

      const updatedAppointments = appointments.map((item) => {
        if (item.id === id) {
          return { ...item, status: status };
        }
        return item;
      });
      wx.setStorageSync("appointments", updatedAppointments);

      // 如果取消预约，重新计算排队
      if (status === 4) {
        this.recalculateQueueNumbers();
      }
    } catch (error) {}
  },

  // 重新计算排队号码
  recalculateQueueNumbers() {
    const appointments = wx.getStorageSync("appointments") || [];

    // 确保 appointments 是数组
    if (!Array.isArray(appointments)) {
      wx.setStorageSync("appointments", []);
      return;
    }

    // 按日期分组预约
    const appointmentsByDate = {};
    appointments.forEach((apt) => {
      if (apt.status !== 4) {
        // 排除已取消的预约
        const date = apt.appointment_date;
        if (!appointmentsByDate[date]) {
          appointmentsByDate[date] = [];
        }
        appointmentsByDate[date].push(apt);
      }
    });

    // 为每个日期的预约重新分配排队号码
    Object.keys(appointmentsByDate).forEach((date) => {
      const dayAppointments = appointmentsByDate[date];
      // 按创建时间排序，确保先预约的排在前面
      dayAppointments.sort(
        (a, b) => new Date(a.created_at) - new Date(b.created_at)
      );

      // 重新分配排队号码（每天从1开始）
      dayAppointments.forEach((apt, index) => {
        const newQueueNumber = index + 1;
        const newEstimatedTime = this.calculateEstimatedTime(
          date,
          apt.appointment_time,
          newQueueNumber
        );

        // 更新预约数据
        const appointmentIndex = appointments.findIndex((a) => a.id === apt.id);
        if (appointmentIndex !== -1) {
          appointments[appointmentIndex].queue_number = newQueueNumber;
          appointments[appointmentIndex].estimated_time = newEstimatedTime;
        }
      });
    });

    // 保存更新后的预约数据
    wx.setStorageSync("appointments", appointments);
  },

  // 计算各状态预约数量
  calculateAppointmentCounts(appointments) {
    const totalCount = appointments.length;
    const pendingCount = appointments.filter(
      (item) => item.status === "pending"
    ).length;
    const completedCount = appointments.filter(
      (item) => item.status === "completed"
    ).length;
    const cancelledCount = appointments.filter(
      (item) => item.status === "cancelled"
    ).length;

    this.setData({
      totalCount,
      pendingCount,
      completedCount,
      cancelledCount,
    });
  },

  // 检查某天是否已约满
  checkIfDayIsFull(date) {
    try {
      const appointments = wx.getStorageSync("appointments") || [];

      // 确保 appointments 是数组
      if (!Array.isArray(appointments)) {
        return false;
      }

      // 获取同一天的所有有效预约（排除已取消的）
      const sameDayAppointments = appointments.filter(
        (apt) => apt.appointment_date === date && apt.status !== 4
      );

      // 检查是否已满（简化版本，不再计算最大预约数）
      const isFull = false; // 让后端处理预约限制

      return isFull;
    } catch (error) {
      return false;
    }
  },

  // 格式化预计时间显示
  formatEstimatedTime(estimatedTime) {
    if (!estimatedTime) return "";
    try {
      let date;
      // 处理不同的时间格式
      if (typeof estimatedTime === "string") {
        // 如果是字符串，直接解析
        date = new Date(estimatedTime);
      } else if (typeof estimatedTime === "object" && estimatedTime.value) {
        // 如果是对象且有value属性
        date = new Date(estimatedTime.value);
      } else {
        return "时间计算中...";
      }

      if (isNaN(date.getTime())) {
        return "时间计算中...";
      }

      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");

      // 只显示时间部分，格式为 HH:MM
      const result = `${hours}:${minutes}`;
      return result;
    } catch (error) {
      return "时间计算中...";
    }
  },

  /**
   * 格式化预约时间，只显示时分
   */
  formatAppointmentTime(appointmentTime) {
    if (!appointmentTime) return "";
    try {
      // 如果已经是 HH:MM 格式，直接返回
      if (
        typeof appointmentTime === "string" &&
        /^\d{2}:\d{2}$/.test(appointmentTime)
      ) {
        return appointmentTime;
      }

      // 如果是 HH:MM:SS 格式，去掉秒
      if (
        typeof appointmentTime === "string" &&
        /^\d{2}:\d{2}:\d{2}$/.test(appointmentTime)
      ) {
        return appointmentTime.substring(0, 5); // 取前5个字符 "HH:MM"
      }

      // 如果是其他格式，尝试解析
      let date;
      if (typeof appointmentTime === "string") {
        date = new Date(appointmentTime);
      } else if (typeof appointmentTime === "object" && appointmentTime.value) {
        date = new Date(appointmentTime.value);
      } else {
        return appointmentTime.toString();
      }

      if (isNaN(date.getTime())) {
        return appointmentTime.toString();
      }

      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");

      return `${hours}:${minutes}`;
    } catch (error) {
      return appointmentTime.toString();
    }
  },

  /**
   * 格式化日期，只显示年月日
   */
  formatDateOnly(dateString) {
    if (!dateString) return "";

    try {
      // 处理各种日期格式
      let dateOnly = dateString;

      // 如果包含时间部分，只取日期部分
      if (dateString.includes(" ")) {
        dateOnly = dateString.split(" ")[0];
      } else if (dateString.includes("T")) {
        dateOnly = dateString.split("T")[0];
      }

      // 确保是有效的日期格式
      if (dateOnly && dateOnly.match(/^\d{4}-\d{2}-\d{2}$/)) {
        return dateOnly;
      }

      // 如果已经是正确的日期格式，直接返回
      if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) {
        return dateString;
      }

      // 尝试解析日期并重新格式化
      try {
        const date = new Date(dateString);
        if (!isNaN(date.getTime())) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, "0");
          const day = String(date.getDate()).padStart(2, "0");
          return `${year}-${month}-${day}`;
        }
      } catch (parseError) {
        console.warn("日期解析失败:", dateString, parseError);
      }

      return ""; // 如果格式不正确，返回空字符串而不是原字符串
    } catch (error) {
      console.warn("日期格式化错误:", dateString, error);
      return "";
    }
  },

  /**
   * 复制文本
   */
  copyText(event) {
    const text = event.currentTarget.dataset.text;
    const type = event.currentTarget.dataset.type;

    if (!text) {
      wx.showToast({
        title: "复制失败",
        icon: "none",
      });
      return;
    }

    wx.setClipboardData({
      data: text,
      success: () => {
        wx.showToast({
          title: `已复制`,
          icon: "success",
          duration: 1500,
        });
      },
      fail: () => {
        wx.showToast({
          title: "复制失败",
          icon: "none",
        });
      },
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "甲年华美甲美睫 - 预约管理",
      desc: "管理您的预约记录，查看预约状态",
      path: "/pages/appointmentManage/index",
      imageUrl: "/images/share-appointment-manage.jpg",
    };
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: "甲年华美甲美睫 - 预约管理",
      query: "",
      imageUrl: "/images/share-appointment-manage.jpg",
    };
  },
});
